package com.zh.webcommon.common.filter;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

import static com.zh.webcommon.HeaderConst.*;

/**
 * 拦截feign的client端远程调用
 *
 * @author ZH
 * @date 22:27 2021/12/25
 */
@Slf4j
public class UserHeaderFeignInterceptor implements RequestInterceptor {
    //默认值""
    @Value("${client.appId:}")
    private String appId;
    //默认值""
    @Value("${client.token:}")
    private String token;

    public UserHeaderFeignInterceptor() {
        log.info("[UserHeaderFeignInterceptor] constructor ...");
    }

    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        if (Objects.nonNull(requestAttributes)) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

            var userType = request.getHeader(HEADER_USER_TYPE);
            var userStr = request.getHeader(HEADER_USER_INFO);
            var uuid = request.getHeader(HEADER_AID);
            var tenantId = request.getHeader(HEADER_TENANT_ID);

            if (StringUtils.hasText(userStr)) {
                template.header(HEADER_USER_INFO, userStr);
            }
            if (StringUtils.hasText(userType)) {
                template.header(HEADER_USER_TYPE, userType);
            }
            if (StringUtils.hasText(uuid)) {
                template.header(HEADER_AID, uuid);
            }
            if (StringUtils.hasText(tenantId)) {
                template.header(HEADER_TENANT_ID, tenantId);
            }
        }

        if (StringUtils.hasText(appId)) {
            template.header(HEADER_APP_ID, appId);
        }
        if (StringUtils.hasText(token)) {
            template.header(HEADER_AUTH, HEADER_AUTH_PREFIX + token); //注意：可能会覆盖原有的token值
        }
    }
}
